﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Super.Framework.Common.Web;

namespace Developer.Web.Areas.Admin.Controllers
{
    public class UploadController : BaseController
    {
        //
        // GET: /admin/Upload/

        public ActionResult Index()
        {
            Response.Charset = "UTF-8";

            // 初始化一大堆变量
            string inputname = "filedata";//表单文件域name
            string attachdir = "/attached";     // 上传文件保存路径，结尾不要带/
            int dirtype = 1;                 // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
            int maxattachsize = 20971520;     // 最大上传大小，默认是20M
            string upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid,docx,doc,xlsx,xls,avi,mp4,flv,pdf";    // 上传扩展名
            int msgtype = 2;                 //返回上传参数的格式：1，只返回url，2，返回参数数组
            byte[] file;                     // 统一转换为byte数组处理
            string localname = "";
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

            string err = "";
            string msg = "''";

            var ctype = Query.Value("type");

            if (disposition != null)
            {
                // HTML5上传
                file = Request.BinaryRead(Request.TotalBytes);
                localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名
            }
            else
            {
                var filecollection = Request.Files;
                var postedfile = filecollection.Get(inputname);
                if (ctype == "kd" || ctype == "kds")
                {
                    postedfile = filecollection[0];
                }

                // 读取原始文件名
                localname = postedfile.FileName;
                // 初始化byte长度.
                file = new Byte[postedfile.ContentLength];

                // 转换为byte类型
                System.IO.Stream stream = postedfile.InputStream;
                stream.Read(file, 0, postedfile.ContentLength);
                stream.Close();

                filecollection = null;
            }

            if (file.Length == 0) err = "无数据提交";
            else
            {
                if (file.Length > maxattachsize) err = "文件大小超过" + maxattachsize + "字节";
                else
                {
                    string attach_dir, attach_subdir, filename, extension, target;

                    // 取上载文件后缀名
                    extension = GetFileExt(localname);

                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上传文件扩展名必需为：" + upext;
                    else
                    {
                        if (extension == "jpg" || extension == "gif" || extension == "png" || extension == "jpeg")
                        {
                            if (file.Length > 1048576)
                            {
                                err = "文件大小超过" + 1048576 + "字节";
                                return Json(new { error = 1, message = err }, JsonRequestBehavior.AllowGet);
                            }

                        }

                        switch (dirtype)
                        {
                            case 2:
                                attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
                                break;
                            case 3:
                                attach_subdir = "ext_" + extension;
                                break;
                            default:
                                attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                                break;
                        }
                        attach_dir = attachdir + "/" + attach_subdir + "/";

                        // 生成随机文件名
                        var random = new Random(DateTime.Now.Millisecond);
                        filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;

                        target = attach_dir + filename;
                        try
                        {
                            CreateFolder(Server.MapPath(attach_dir));

                            var fs = new System.IO.FileStream(Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            fs.Write(file, 0, file.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception ex)
                        {
                            err = ex.Message.ToString();
                        }
                        var path = target;

                        target = jsonString(target);
                        if (msgtype == 1)
                        {
                            msg = "'" + target + "'";
                        }
                        else
                        {
                            msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
                        }
                        if (ctype == "kd" || ctype == "kds")
                        {
                            msg = "{'url':'" + target + "','error':'0'}";
                            return Json(new { error = 0, url = path }, JsonRequestBehavior.AllowGet);
                        }


                    }
                }
            }

            file = null;

            if (ctype == "kd")
            {
                return Json(new { error = err, url = "" }, JsonRequestBehavior.AllowGet);
            }

            if (ctype == "kds")
            {
                return Json(new { error = 1, message = err }, JsonRequestBehavior.AllowGet);
            }
            return Content("{'error':'" + jsonString(err) + "','msg':" + msg + "}");

        }


        public string jsonString(string str)
        {
            str = str.Replace("\\", "\\\\");
            str = str.Replace("/", "\\/");
            str = str.Replace("'", "\\'");
            return str;
        }

        /// <summary>
        /// 获取文件后缀名
        /// </summary>
        /// <param name="fullPath">文件的完整路径</param>
        /// <returns></returns>
        public string GetFileExt(string fullPath)
        {
            return fullPath != "" ? fullPath.Substring(fullPath.LastIndexOf('.') + 1).ToLower() : "";
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="folderPath">文件夹路径</param>
        public void CreateFolder(string folderPath)
        {
            if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);
        }


        /// <summary>
        /// image
        /// </summary>
        /// <returns></returns>
        public ActionResult imageUpload()
        {
            Response.Charset = "UTF-8";

            // 初始化一大堆变量
            string inputname = "filedata";//表单文件域name
            string attachdir = "/File";     // 上传文件保存路径，结尾不要带/
            int dirtype = 1;                 // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
            int maxattachsize = 104857600;     // 最大上传大小，默认是50M
            string upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid,docx,doc,xlsx,xls,avi,mp4,flv";    // 上传扩展名
            int msgtype = 2;                 //返回上传参数的格式：1，只返回url，2，返回参数数组
            byte[] file;                     // 统一转换为byte数组处理
            string localname = "";
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

            string err = "";
            string msg = "''";

            var ctype = Query.Value("type");

            if (disposition != null)
            {
                // HTML5上传
                file = Request.BinaryRead(Request.TotalBytes);
                localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名
            }
            else
            {
                var filecollection = Request.Files;
                var postedfile = filecollection.Get(inputname);
                if (ctype == "kd")
                {
                    postedfile = filecollection[0];
                }

                // 读取原始文件名
                localname = postedfile.FileName;
                // 初始化byte长度.
                file = new Byte[postedfile.ContentLength];
                // 转换为byte类型
                System.IO.Stream stream = postedfile.InputStream;
                stream.Read(file, 0, postedfile.ContentLength);
                stream.Close();

                filecollection = null;
            }

            if (file.Length == 0) err = "无数据提交";
            else
            {
                if (file.Length > maxattachsize) err = "文件大小超过" + maxattachsize + "字节";
                else
                {
                    string attach_dir, attach_subdir, filename, extension, target;

                    // 取上载文件后缀名
                    extension = GetFileExt(localname);

                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上传文件扩展名必需为：" + upext;
                    else
                    {
                        switch (dirtype)
                        {
                            case 2:
                                attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
                                break;
                            case 3:
                                attach_subdir = "ext_" + extension;
                                break;
                            default:
                                attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                                break;
                        }
                        attach_dir = attachdir + "/" + attach_subdir + "/";

                        // 生成随机文件名
                        var random = new Random(DateTime.Now.Millisecond);
                        filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;

                        target = attach_dir + filename;
                        try
                        {
                            CreateFolder(Server.MapPath(attach_dir));

                            var fs = new System.IO.FileStream(Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            fs.Write(file, 0, file.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception ex)
                        {
                            err = ex.Message.ToString();
                        }
                        var path = target;

                        target = jsonString(target);
                        if (msgtype == 1)
                        {
                            msg = "'" + target + "'";
                        }
                        else
                        {
                            msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
                        }
                        if (ctype == "kd")
                        {
                            msg = "{'url':'" + target + "','error':'0'}";
                            return Json(new { error = 0, url = path }, JsonRequestBehavior.AllowGet);
                        }
                    }
                }
            }

            file = null;

            if (ctype == "kd")
            {
                return Json(new { error = err, url = "" }, JsonRequestBehavior.AllowGet);
            }


            return Content("{'err':'" + jsonString(err) + "','msg':" + msg + "}");

        }

    }
}
